"""fixed_gcp_tenant_account_id

Revision ID: b300318bb5e7
Revises: 03b8dc8f3916
Create Date: 2025-02-06 12:24:50.051324

"""
import os
import json
import logging
import sqlalchemy as sa
import cryptocode
from alembic import op
from optscale_client.config_client.client import Client as EtcdClient
from sqlalchemy import select, update, and_
from sqlalchemy.orm import Session
from sqlalchemy.sql import table, column

# revision identifiers, used by Alembic.
revision = 'b300318bb5e7'
down_revision = '03b8dc8f3916'
branch_labels = None
depends_on = None

DEFAULT_ETCD_HOST = 'etcd-client'
DEFAULT_ETCD_PORT = 80
LOG = logging.getLogger(__name__)
KEY = "/encryption_salt"


def _get_etcd_config_client():
    etcd_host = os.environ.get('HX_ETCD_HOST', DEFAULT_ETCD_HOST)
    etcd_port = os.environ.get('HX_ETCD_PORT', DEFAULT_ETCD_PORT)
    config_cl = EtcdClient(host=etcd_host, port=int(etcd_port))
    return config_cl


def _get_encryption_salt():
    config_cl = _get_etcd_config_client()
    return config_cl.encryption_salt()


def decode_config(encoded_str):
    s = _get_encryption_salt()
    return json.loads(cryptocode.decrypt(encoded_str, s))


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    session = Session(bind=bind)
    try:
        cloud_acc_table = table(
            'cloudaccount',
            column('id', sa.String(36)),
            column('type', sa.String(36)),
            column('config', sa.Text()),
            column('account_id', sa.String(256)),
            column('deleted_at', sa.Integer())
        )
        cmd = select([
            cloud_acc_table.c.id, cloud_acc_table.c.config
        ]).where(and_(
            cloud_acc_table.c.type == 'GCP_TENANT',
            cloud_acc_table.c.deleted_at == 0,
            cloud_acc_table.c.account_id.is_(None)
        ))
        cloud_accounts = session.execute(cmd)
        for ca in cloud_accounts:
            conf = decode_config(ca['config'])
            account_id = conf.get('credentials', {}).get('client_id')
            if not account_id:
                LOG.warning('Found unusual credentials: %s' % ca['id'])
                continue
            upd_stmt = update(cloud_acc_table).values(
                account_id=account_id
            ).where(cloud_acc_table.c.id == ca['id'])
            session.execute(upd_stmt)
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    session = Session(bind=bind)
    try:
        cloud_acc_table = table(
            'cloudaccount',
            column('type', sa.String(36)),
            column('account_id', sa.String(256))
        )
        upd_stmt = update(cloud_acc_table).values(
            account_id=None
        ).where(cloud_acc_table.c.type == 'GCP_TENANT')
        session.execute(upd_stmt)
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()
    # ### end Alembic commands ###
